package main

import (
	"bufio"
	"crypto/sha1"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"regexp"
	"strings"
)

const hostsDIR = `C:\Windows\System32\drivers\etc\hosts`
const hostsURL = `https://raw.githubusercontent.com/racaljk/hosts/master/hosts`

func getDate(b []byte) string {
	reg := regexp.MustCompile(`Last updated: ([0-9\-]+)`)
	if reg.Match(b) {
		datab := reg.FindSubmatch(b)[1]
		return string(datab)
	}
	return ``
}

func getGitSha1(b []byte) string {
	tmp := []byte(fmt.Sprintf("blob %d\x00%s", len(b), b))
	return fmt.Sprintf(`%x`, sha1.Sum(tmp))
}

func main() {
	client := &http.Client{}
	req, _ := http.NewRequest("GET", hostsURL, nil)
	b, _ := ioutil.ReadFile(hostsDIR)
	date := getDate(b)
	var oldHash string
	if date != `` {
		oldHash = getGitSha1(b)
		fmt.Println(`本地版本：`)
		fmt.Printf("%s %s\n", date, oldHash)
		req.Header.Add("If-None-Match", fmt.Sprintf(`"%s"`, oldHash))
	} else {
		fmt.Println(`本地版本未知`)
	}
	res, _ := client.Do(req)
	if res.StatusCode == 200 {
		resText, _ := ioutil.ReadAll(res.Body)
		resHash := strings.Trim(res.Header["Etag"][0], `"`)
		if oldHash != resHash {
			fmt.Println(`检测到最新版：`)
			fmt.Printf("%s %s\n", getDate(resText), resHash)
			ioutil.WriteFile(hostsDIR, resText, 0644)
			fmt.Println(`已更新至最新版`)
		}
	} else if res.StatusCode == 304 {
		fmt.Println(`已是最新版`)
	} else {
		fmt.Printf("请求失败，错误码%s\n", res.Status)
	}
	fmt.Println(`按回车键结束程序`)
	bufio.NewReader(os.Stdin).ReadLine()
}
